const jwt = require('jsonwebtoken')

//定义密钥，根据需求修改
const secret = 'asdasdsadsxzc'

//定义短token过去时间
const accessTokenTime = 20

//定义长token过期时间
const refreshTokenTime = 60*60*24

//定义短Token
const setAccessToken=(user={})=>{
    return 'Bearer' + jwt.sign(user,secret,{expiresIn:accessTokenTime})
}

//定义长Token
const setRefreshToken=(user={})=>{
    return 'Bearer' + jwt.sign(user,secret,{expiresIn:refreshTokenTime})
}

//验证短token是否过期
const testAccessToken=(token)=>{
    let code =200
    if(!token){
        return{
            code:401,
            msg:'未登录或token不存在'
        }
    }
    jwt.verify(token,secret,(err,data)=>{
        if(err){
            if(err.message == 'invalid token'){
                code = 402
                msg ='无效的token'
                return
            }
            if(err.message =='jwt expired'){
                code = 402
                msg = 'token过期'
                return
            }
            code = 402
            msg = '未知token错误'
            return
        }
        code = 200
        msg ='有效的token'
        return
    })
    return{
        code,
        msg
    }
}

//验证长token是否过期
const testRefReshToken =(token,user)=>{
    let code = 200
    let newtoken = ''
    jwt.verify(token,secret,(err,data)=>{
        if(err){
            if(err.message == 'invalid token'){
                code = 402
                msg = '无效的token'
                return
            }
            if(err.message == 'jwt expired'){
                code = 402 
                msg ='token过期'
                return
            }
            code = 402 
            msg = '未知token错误'
            return
        }
        code = 200
        msg = '有效的token'
        newtoken = setAccessToken(user)
        return
    })
    return{
        code,
        msg,
        newtoken
    }
}

module.exports={
    setAccessToken,
    setRefreshToken,
    testAccessToken,
    testRefReshToken
}